package com.wei.frame.utils;

import androidx.annotation.Nullable;

import com.wei.frame.framework.IView;
import com.wei.frame.ui.lifecycle.LifecycleProvider;
import com.wei.frame.ui.lifecycle.LifecycleTransformer;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：赵若位
 * 时间：2020/8/20 11:24
 * 邮箱：1070138445@qq.com
 * 功能：RxJava工具类
 */
public class RxUtils {
    private RxUtils() {
        throw new IllegalStateException("You can't instantiate me~");
    }


    /*RxJava展示进度条*/
    public static <T> ObservableTransformer<T, T> applyLoading(IView view) {
        return observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    if (null != view) {
                        view.showLoading();
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    if (null != view) {
                        view.hideLoading();
                    }
                }).unsubscribeOn(Schedulers.io());
    }

    /*RxJava线程切换*/
    public static <T> ObservableTransformer<T, T> applySchedulers() {
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io());
    }


    //TODO 需要检测Rxjava有没有内存泄漏
    public static <T> LifecycleTransformer<T> applyLifecycle(@Nullable IView view) {
        Preconditions.checkNotNull(view, "The Lifecycle is null~");
        if (view instanceof LifecycleProvider) {
            return ((LifecycleProvider) view).bindToLifecycle();
        } else {
            throw new IllegalStateException("The IView isn't LifecycleProvider~");
        }
    }
}
